package me.mritd.quartz.execute;

import java.awt.TrayIcon;

import me.mritd.quartz.job.SendEmailJob;
import me.mritd.quartz.listener.EmailJobListener;
import me.mritd.vo.EmailVo;
import me.mritd.vo.QuartzInfoVo;

import org.apache.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.Trigger.TriggerState;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.KeyMatcher;

/**
 * 
 * @ClassName JobExecute 
 * @Description TODO JOB启动执行类
 * @author 漠然  mritd@mritd.me
 * @date 2015年10月6日 下午5:32:46 
 * @version 1.0
 */
public class EmailJobExecute {
	
	private TrayIcon trayIcon;
	private Scheduler scheduler;
	private final Logger logger = Logger.getLogger(EmailJobExecute.class);
	
	/**
	 * 
	 * @Title StartSendEmail 
	 * @Description TODO 启动调度器，并启动任务
	 * @param executionRules cron计时表达式
	 * @return boolean
	 * @throws
	 */
	public boolean startSendEmail(QuartzInfoVo quartzInfo,EmailVo mailInfo){

		if (mailInfo==null||quartzInfo.getCron()==null||quartzInfo.getCron().trim().equals("")) {
			logger.error("###### 启动定时任务时，mailInfo或quartzInfo为空!");
			return false;
		}
		//创建Job初始化信息对象
		JobDetail job = JobBuilder.newJob(SendEmailJob.class).withIdentity(quartzInfo.getJobKey()).build();
		
		//创建触发器
		Trigger trigger = TriggerBuilder
				.newTrigger()
				.withIdentity(quartzInfo.getTiggerKey())
				.withSchedule(CronScheduleBuilder.cronSchedule(quartzInfo.getCron()))
				.build();
		
		//创建监听器 
		EmailJobListener emailJobListener = new EmailJobListener();
		
		//获取目标job参数Map 向其传递邮件发送参数
		JobDataMap jobDataMap = job.getJobDataMap();
		jobDataMap.put("mailInfo", mailInfo);
		jobDataMap.put("trayIcon", trayIcon);
				
		
		try {
			
			//加入任务和其匹配的调度器
			scheduler.scheduleJob(job, trigger);
			//添加监听器
			scheduler.getListenerManager().addJobListener(emailJobListener, KeyMatcher.keyEquals(quartzInfo.getJobKey()));
			
		} catch (SchedulerException e) {
			logger.error("###### 定时任务 调度器创建失败!");
			logger.error("异常信息: ", e);
			return false;
		}
		
		logger.info("###### 定时任务 SendEmail 启动成功!");
		return true;
		
	}
	
	/**
	 * 
	 * @Title StopSendEmail 
	 * @Description TODO 停止调度器
	 * @return boolean
	 * @throws
	 */
	public boolean stopSendEmail(){
		try {
			Scheduler scheduler = new StdSchedulerFactory().getScheduler();
			scheduler.unscheduleJob(new TriggerKey("SendEmailTrigger", "DailyGroup"));
			logger.info("###### Email Trigger停止成功!");
			return true;
		} catch (SchedulerException e) {
			logger.info("###### Email Trigger停止失败!");
			logger.error("异常信息: ", e);
			return false;
		}
	}

	/**
	 * 
	 * @Title schedulerStatus 
	 * @Description TODO 判断调度器是否启动
	 * @return boolean true:启动  false:停止
	 * @throws
	 */
	public boolean schedulerStatus(){
		
		boolean started = false;
		boolean stoped = false;
		try {
			Scheduler scheduler = new StdSchedulerFactory().getScheduler();
			started = scheduler.isStarted();
			stoped = scheduler.isShutdown();
		} catch (SchedulerException e) {
			logger.error("###### 监测调度器启动状态时获取调度器出现异常!");
			logger.error("异常信息: ", e);
		}
		
		if (started&&!stoped) return true;
		else if (!started&&stoped) return false;
		
		return false;
		
	}
	
	/**
	 * 
	 * @Title emailJobStatus 
	 * @Description TODO 监测任务状态
	 * @return TriggerState
	 * @throws
	 */
	public TriggerState emailJobStatus(){
		
		try {
			StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();
			Scheduler scheduler = schedulerFactory.getScheduler();
			TriggerState state =  scheduler.getTriggerState(new TriggerKey("SendEmailTrigger", "DailyGroup"));
			return state;
		} catch (SchedulerException e) {
			logger.error("###### 监测任务状态时获取调度器出现异常!");
			logger.error("异常信息: ", e);
			return null;
		}
		
	}
	
	
	
	
	
	
	
	
	
	public TrayIcon getTrayIcon() {
		return trayIcon;
	}

	public void setTrayIcon(TrayIcon trayIcon) {
		this.trayIcon = trayIcon;
	}

	public EmailJobExecute() {
		super();
		//创建调度器
		try {
			scheduler = new StdSchedulerFactory().getScheduler();
		} catch (SchedulerException e) {
			logger.error("###### 初始化调度器失败: ", e);
		}
	}


	
	
	
}
